package com.gjs.cd.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gjs.cd.mapper.CdDetailMapper;
import com.gjs.cd.pojo.dto.CdDetailReq;
import com.gjs.cd.pojo.dto.StatusReq;
import com.gjs.cd.pojo.dto.TotalReq;
import com.gjs.cd.pojo.entity.CdDetail;
import com.gjs.cd.pojo.vo.CdDetailVo;
import com.gjs.cd.service.ICdCodeGenerateBatchService;
import com.gjs.cd.service.ICdDetailService;
import com.gjs.cd.service.ICdResourceService;
import com.gjs.common.exception.BizException;
import com.gjs.common.microservice.api.IResourceMicroService;
import com.gjs.common.pojo.dto.request.PageQuery;
import com.gjs.common.pojo.dto.resource.TypeDTO;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toMap;

/**
 * @author zhongwenguang
 * @date 2022-3-16 9:28
 */
@Service
public class CdDetailServiceImpl extends ServiceImpl<CdDetailMapper, CdDetail> implements ICdDetailService {
    @DubboReference
    private IResourceMicroService iResourceMicroService;

    @Autowired
    private ICdResourceService iCdResourceService;

    @Autowired
    private ICdCodeGenerateBatchService iCdCodeGenerateBatchService;

    //获取分页列表数据
    @Override
    public IPage<CdDetailVo> getList(PageQuery pageQuery, CdDetailReq cdDetailReq) {
        IPage<CdDetail> cdDetailIPage = this.page(pageQuery.buildPage(),this.buildWrapper(cdDetailReq));
        List<Long> cdIds = new ArrayList<>();
        //类型转换
        IPage<CdDetailVo> cdDetailVoIPage = cdDetailIPage.convert(u->{
           CdDetailVo v = new CdDetailVo();
           BeanUtil.copyProperties(u,v);
           cdIds.add(u.getId());
           return v;
        });
        if (cdDetailVoIPage.getRecords().size() > 0){
            //微服务获取学科
            List<TypeDTO> subjectList = iResourceMicroService.listSubjects();
            Map<Long,String> subjectMap = subjectList.stream().collect(toMap(TypeDTO::getKey,TypeDTO::getText));
            //微服务获取学段
            List<TypeDTO> periodsList = iResourceMicroService.listPeriods();
            Map<Long,String> periodsMap = periodsList.stream().collect(toMap(TypeDTO::getKey,TypeDTO::getText));

            //统计批次
            List<TotalReq> totalCdCodeGenerateBatchList = iCdCodeGenerateBatchService.getTotalByIds(cdIds);
            Map<Long,Long> toCdCodeGenerateBathchMap = totalCdCodeGenerateBatchList.size()>0 ? totalCdCodeGenerateBatchList.stream().collect(toMap(TotalReq::getId,TotalReq::getTotal)):null;

            //统计光盘（品种）对应的资源数量
            List<TotalReq> totalCdResourceList = iCdResourceService.getTotalByIds(cdIds);
            Map<Long,Long> totalCdResourceMap = totalCdResourceList.size()>0 ? totalCdResourceList.stream().collect(toMap(TotalReq::getId,TotalReq::getTotal)):null;

            cdDetailVoIPage.convert(u->{
                //设置学段名称
                u.setPeriodName(periodsMap.get(u.getPeriodId()));
                //设置学科名称
                u.setSubjectName(subjectMap.get(u.getSubjectId()));
                if (totalCdResourceMap!=null){
                    u.setResourceNum(totalCdResourceMap.get(u.getId()));
                }
                if (toCdCodeGenerateBathchMap != null){
                    u.setGenerateNum(toCdCodeGenerateBathchMap.get(u.getId()));
                }
                return u;
            });
        }
        return cdDetailVoIPage;
    }

    //光盘（品种）上下架操作
    @Override
    public Boolean putOrOff(List<StatusReq> list) {
        List<CdDetail> cdDetailList = Lists.transform(list, u->{
            CdDetail cdDetail = new CdDetail();
            cdDetail.setStatus(u.getStatus());
            cdDetail.setId(u.getId());
            return cdDetail;
        });
        try{
            this.updateBatchById(cdDetailList);
        }catch (Exception e){
            throw new BizException("操作失败！");
        }
        return true;
    }

    @Override
    public Boolean putOrOffOne(StatusReq statusReq) {
        CdDetail cdDetail = BeanUtil.copyProperties(statusReq,CdDetail.class);
        return this.updateById(cdDetail);
    }

    @Override
    public CdDetail detail(Long id) {
        CdDetail cdDetail = this.getById(id);
        return cdDetail;
    }

    @Override
    public Wrapper<CdDetail> buildWrapper(CdDetailReq req) {
        //查询条件:品种名称(模糊查询)、状态、学科、创建时间
        LambdaQueryWrapper<CdDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotBlank(req.getCdName()),CdDetail::getCdName,req.getCdName());
        lambdaQueryWrapper.eq(req.getStatus() != null,CdDetail::getStatus,req.getStatus());
        lambdaQueryWrapper.eq(req.getSubjectId() != null,CdDetail::getSubjectId,req.getSubjectId());
        lambdaQueryWrapper.eq(req.getPeriodId() != null,CdDetail::getPeriodId,req.getPeriodId());
        lambdaQueryWrapper.between((req.getBeginTime() != null && req.getEndTime() != null),CdDetail::getCreateTime,req.getBeginTime(),req.getEndTime());
        lambdaQueryWrapper.orderByDesc(CdDetail::getId);
        return lambdaQueryWrapper;
    }
}
